package com.home.fansea.aspact;

import com.google.common.util.concurrent.RateLimiter;
import com.home.fansea.annotation.ApiRateLimit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class ApiRateLimitAspect {

    private final Map<String, RateLimiter> rateLimiters = new ConcurrentHashMap<>();

    @Before("@annotation(apiRateLimit)")
    public void limit(JoinPoint joinPoint, ApiRateLimit apiRateLimit) {
        String methodName = joinPoint.getSignature().toLongString();
        double qps = apiRateLimit.qps();
        /*k是一个键，用于在rateLimiters映射中查找或存储RateLimiter对象。
        RateLimiter.create(qps)是RateLimiter类的构造函数，
        它接受一个double类型的参数qps，表示每秒钟允许进入缓冲器的元素数量。*/
        RateLimiter limiter = rateLimiters.computeIfAbsent(methodName, k -> RateLimiter.create(qps));
        long timeout = apiRateLimit.timeout();
        TimeUnit timeUnit = apiRateLimit.timeUnit();
        if (timeout > 0) {
            if (!limiter.tryAcquire(timeout, timeUnit)) {
                throw new RuntimeException("API rate limit exceeded");
            }
        } else {
            if (!limiter.tryAcquire()) {
                throw new RuntimeException("API rate limit exceeded");
            }
        }
    }
}
